package core

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

const NOTGROUP = "不在分组内"

type FileVideos struct {
	Desc     string
	Time 	 string
	Num		 int
	Seconds  int
	offset   bool
}

func (v *FileVideos) TimeStr() string {

	if v.Time != "" {
		return v.Time
	}

	v.Time = ResolveTime(v.Second())
	return v.Time
}

func (v *FileVideos) Second() int {

	if v.offset {
		return v.Seconds
	}

	v.Seconds = v.Seconds + offsetCorrection(v.Num)
	v.offset = true
	return v.Seconds
}


type Option struct {
	FilePath string
	Where	 string
	SuffixType string
}

type State struct {
	filepath string
	where string
	suffixType string

	nums    map[string]int
	seconds map[string]int

	totalNum int
	totalSeconds int

	TimerStr
}

func NewState(opt Option) *State {
	return &State{
		filepath: opt.FilePath,
		where: opt.Where,
		suffixType: opt.SuffixType,

		nums: make(map[string]int),
		seconds: make(map[string]int),
	}
}

func (s *State) FilePathState() (rets []*FileVideos,err error) {

	defer func() {
		if e := recover(); e != nil {
			err = errors.New("系统错误，请注意检查路径或稍后重试 path:" +s.filepath)
		}
	}()

	if s.filepath == "" {
		return nil,ErrFilPathNULL
	}
	total := &FileVideos{
		Desc: "整体",
		Time:     "",
		Num:      0,
		Seconds:  0,
		offset:   true,
	}
	rets = append(rets, total)

	var mp4 Mp4
	// 根据目录读取文件
	filepath.Walk(s.filepath, func(pathStr string, info os.FileInfo, err error) error {
		// 获取文件，并判断是否为mp4
		ts := strings.Split(s.suffixType, ",")
		if len(ts) == 0 {
			ts = []string{".mp4"}
		}

		for _, t := range ts {
			if strings.Index(info.Name(), t) != -1 {
				// 路径地址
				path := pathStr[:len(pathStr) - len(info.Name())]

				if s.where != "" {
					// 判断是否存在，不存在就跳过
					if strings.Index(path, s.where) == -1 {
						return nil
					}
				}

				_, second,_ := mp4.GetMp4Duration(pathStr)

				s.totalNum ++

				if len(rets) != 1 {
					fv := rets[len(rets)-1]
					if fv.Desc == path {
						fv.Seconds+= second
						fv.Num++
						return nil
					}
					fv.TimeStr()
					s.totalSeconds += fv.Second()
				}

				v := &FileVideos{
					Desc: path,
					Num:      1,
					Seconds:  second,
					offset:   false,
				}

				rets = append(rets, v)
			}
		}
		return nil
	})

	fv := rets[len(rets)-1]
	fv.TimeStr()
	s.totalSeconds += fv.Second()

	total.Num = s.totalNum
	total.Seconds = s.totalSeconds
	total.TimeStr()


	return rets, nil
}



func (s *State) Groups(gs []string) ([]*FileVideos,error) {

	fvs,err := s.FilePathState()
	if err != nil {
		return nil, err
	}
	if len(gs) == 0 {
		return fvs, nil
	}

	groupFvs := make(map[string]*FileVideos)
	// 合并
	merge := func(g string, fv *FileVideos) {
		// 存在分组
		gfv,ok := groupFvs[g]
		if !ok {
			// 第一次，就创建对象
			groupFvs[g] = &FileVideos{
				Desc:    g,
				Time:    "",
				Num:     fv.Num,
				Seconds: fv.Second(),
				offset:  true,
			}
		} else {
			// 合并计算
			gfv.Seconds += fv.Second()
			gfv.Num += fv.Num
		}
	}
	// 分组
	for k, fv := range fvs {
		if k == 0 {
			// 整体
			// 计算平均时长
			avg := fv.Seconds / len(gs)
			fv.Time = fmt.Sprintf("总时长:%s, 分组平均时长:%s", fv.Time, ResolveTime(avg))
			groupFvs[fv.Desc] = fv
			continue
		}

		for i, g := range gs {
			if strings.Index(fv.Desc, g) != -1 {
				merge(g, fv)
				break
			} else if i == len(gs) - 1 {
				merge(fv.Desc, fv)
			}
		}
	}
	var rets []*FileVideos
	// 得到信息
	for g, _ := range groupFvs {
		groupFvs[g].TimeStr()
		rets = append(rets, groupFvs[g])
	}

	return rets, nil
}



